using System;
using UnityEngine;

namespace Framework
{
    public class FrameCounter : ReferenceCountable
    {
        protected int _frameCount;
        protected int _invokeCount;
        protected Action<float> _callback;

        protected int _frameCounter;
        protected int _invokeCounter;
        protected float _lastStartTime;
        
        public FrameCounter(int frameCount, int invokeCount, Action<float> callback)
        {
            _frameCount = frameCount;
            _invokeCount = invokeCount;
            _callback = callback;
        }
        
        public bool Update()
        {
            ++_frameCounter;
            if (_frameCounter >= _frameCount)
            {
                float curTime = Time.realtimeSinceStartup;
                float deltaTime = curTime - _lastStartTime;
                _callback.Invoke(deltaTime);
                _frameCounter = 0;
                _lastStartTime = curTime;
                ++_invokeCounter;
                if (_invokeCount > 0 && _invokeCounter >= _invokeCount)
                {
                    return true;
                }
            }
            return false;
        }

        public override bool Equals(object obj)
        {
            return _callback == (Action<float>)obj;
        }

        public void Reset()
        {
            _frameCounter = 0;
            _invokeCounter = 0;
            _lastStartTime = Time.realtimeSinceStartup;
        }
    }
}